<?php
require_once("DBEntity.php");

/**
 * @author Matteo Vigoni <mattevigo@gmail.com>
 * @package DBEntity
 * @version 0.2
 */
class User extends DBEntity{

	/**
	 * Costruttore
	 *
	 * @todo test con il prefix
	 */
	public function __construct(DB $db_wrapper, $uid){

		parent::__construct($db_wrapper, $db_wrapper->t_users, "user_id", $uid);
	}

	/**
	 * Cambia la password utente dopo aver verificato la validita' della vecchia password
	 *
	 * @param string $old_password
	 * @param string $new_password
	 *
	 * @throws DBException per problemi con il database
	 * @throws EntityException se la vecchia password inserita e' sbagliata
	 *
	 * @todo modifica della password nel db con il meccanismo di autenticazione di joomla
	 */
	public function setPassword($old_password, $new_password)
	{
		$mysql_query = "SELECT `user_password`
						FROM `{$this->$db_wrapper->name()}`.`$db_wrapper->t_users`
						WHERE `user_id`=$this->user_id";

		$result = $this->db_wrapper->query($mysql_query);
		$row = mysql_fetch_row($result);
		//echo $row[0] . "<br />";
		//echo $old_password . "<br />";

		if(strcmp($old_password, $row[0]) == 0){

			$mysql_query = "UPDATE `{$db_wrapper->name()}`.`$db_wrapper->t_users`
							SET `user_password`='$new_password'
							WHERE `user_id`={$this->id()}";

			$db_wrapper->query($mysql_query);

		} else throw new EntityException("Password sbagliata");
	}

	public function setEmail($new_email)
	{
		$this->set('user_email', $new_email);
	}

	/**
	 * @deprecated 0.2 - 09/set/2009
	 */
	public function getId()
	{
		return parent::get('user_id');
	}

	public function getUsername()
	{
		return parent::get('user_username');
	}

	/**
	 *
	 */
	public function isAdmin()
	{
		if($this->values['user_admin'] == 1)
		return true;
		else return false;
	}

	/**
	 * Funzione di login, verifica username e password e se questi coincidono con i relativi valori del database
	 * viene restituito un oggetto di tipo <code>User</code> relativo all'utente
	 *
	 * @param DB $db_wrapper
	 * @param string $username
	 * @param string $password
	 *
	 * @throws 	DBException se si sono verificati problemi con il database
	 * 			LoginException
	 * @return un  nuovo <code>User</code>
	 *
	 * @todo modifica del login utilizzando il meccanismo di joomla
	 */
	public static function login(DB $db, $username, $password)
	{
		$user = null;
		$db_query = "	SELECT `user_id` , `user_password`, `user_admin`
						FROM `$db->t_users`
						WHERE `user_username` = '$username'";

		$result = $db->query($db_query);
		$row = mysql_fetch_row($result);
		//echo "user: " . $row[0] . "<br />";
		//echo $db_query."<br />";

		if(count($row) != 3)
		{
			throw new LoginException("Wrong Username");
		}
		else if(strcmp($password, $row[1]) == 0)
		{
			if($row[2] == 1) $user = new Admin($db, $row[0]);
			if($row[2] == 0) $user = new User($db, $row[0]);
		}
		else throw new LoginException("Wrong Password");

		return $user;
	}

	/**
	 * Funzione di login, verifica username e password e se questi coincidono con i relativi valori del database
	 * viene restituito un oggetto di tipo <code>User</code> relativo all'utente
	 *
	 * @param DB $db_wrapper
	 * @param string $username
	 * @param string $password
	 *
	 * @throws 	DBException se si sono verificati problemi con il database
	 * 			LoginException
	 * @return un  nuovo <code>User</code>
	 *
	 * @todo modifica del login utilizzando il meccanismo di joomla
	 */
	public static function jlogin(DB $db, $username, $password)
	{
		$user = null;
		$db_query = "	SELECT `user_id` , `user_password`, `user_admin`
						FROM `$db->t_users`
						WHERE `user_username` = '$username'";

		$result = $db->query($db_query);
		$row = mysql_fetch_row($result);
		//echo "user: " . $row[0] . "<br />";
		//echo $db_query."<br />";

		if(count($row) != 3)
		{
			throw new LoginException("Wrong Username");
		}
		
		$parts	= explode( ':', $row[1] );
		$crypt	= $parts[0];
		$salt	= @$parts[1];
		$testcrypt = User::getCryptedPassword($password, $salt);
		echo $crypt . "==" . $testcrypt ."<br />";

		if ($crypt == $testcrypt) // is autenticate
		{
			if($row[2] == 1) $user = new Admin($db, $row[0]);
			if($row[2] == 0) $user = new User($db, $row[0]);
		}
		else throw new LoginException("Wrong Password");
		
		return $user;
	}

	/**
	 * Formats a password using the current encryption.
	 *
	 * @access	public
	 * @param	string	$plaintext	The plaintext password to encrypt.
	 * @param	string	$salt		The salt to use to encrypt the password. []
	 *								If not present, a new salt will be
	 *								generated.
	 * @param	string	$encryption	The kind of pasword encryption to use.
	 *								Defaults to md5-hex.
	 * @param	boolean	$show_encrypt  Some password systems prepend the kind of
	 *								encryption to the crypted password ({SHA},
	 *								etc). Defaults to false.
	 *
	 * @return string  The encrypted password.
	 */
	function getCryptedPassword($plaintext, $salt = '', $encryption = 'md5-hex', $show_encrypt = false)
	{
		// Get the salt to use.
		$salt = User::getSalt($encryption, $salt, $plaintext);
		echo "Salt: $salt<br />"; 
		echo "Password: $plaintext<br />";

		// Encrypt the password.
		$encrypted = ($salt) ? md5($plaintext.$salt) : md5($plaintext);
		echo "Encrypted: $encrypted : ".md5($plaintext.$salt)."<br />";
		return ($show_encrypt) ? '{MD5}'.$encrypted : $encrypted;
	}

	/**
	 * Returns a salt for the appropriate kind of password encryption.
	 * Optionally takes a seed and a plaintext password, to extract the seed
	 * of an existing password, or for encryption types that use the plaintext
	 * in the generation of the salt.
	 *
	 * @access public
	 * @param string $encryption  The kind of pasword encryption to use.
	 *							Defaults to md5-hex.
	 * @param string $seed		The seed to get the salt from (probably a
	 *							previously generated password). Defaults to
	 *							generating a new seed.
	 * @param string $plaintext   The plaintext password that we're generating
	 *							a salt for. Defaults to none.
	 *
	 * @return string  The generated or extracted salt.
	 */
	function getSalt($encryption = 'md5-hex', $seed = '', $plaintext = '')
	{
		// Encrypt the password.
		$salt = '';
		if ($seed)
		{
			$salt = $seed;
		}
		return $salt;
	}
}

class Admin extends User
{
	/**
	 *
	 */
	function __construct(DB $db_wrapper, $uid)
	{
		parent::__construct($db_wrapper, $uid);
	}

	/**
	 * @todo
	 */
	public function createNewUser($name)
	{

	}
}

class LoginException extends Exception
{
	function __construct($message){
		parent::__construct($message);
	}
}
?>
